package com.xgpro.mobile.archives.service.impl;

import com.xgpro.common.enums.ResultCodeEnum;
import com.xgpro.common.exceptions.BusinessRuntimeException;
import com.xgpro.common.results.ResponseResult;
import com.xgpro.common.utils.FileTool;
import com.xgpro.common.utils.ReadPropertiesUtil;
import com.xgpro.domain.archives.dto.*;
import com.xgpro.domain.archives.entity.*;
import com.xgpro.domain.archives.vo.FileDetails;
import com.xgpro.domain.talentintroduction.entity.User;
import com.xgpro.mapper.archives.ArchivesMapper;
import com.xgpro.mapper.archives.RankApprovalMapper;
import com.xgpro.mapper.archives.RankMapper;
import com.xgpro.mapper.archives.SixSigmaMapper;
import com.xgpro.mapper.talentintroduction.UserMapper;
import com.xgpro.mobile.archives.service.ArchivesService;
import com.xgpro.common.utils.TimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * @program: xgpro__dev
 * @Description:
 * @Author: wangyang
 * @Date: 2019-09-20 22:15
 **/
@Service
@Transactional(readOnly = false)
public class ArchivesServiceImpl implements ArchivesService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private ArchivesMapper archivesMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private RankMapper rankMapper;

    @Resource
    private RankApprovalMapper rankApprovalMapper;

    @Resource
    private SixSigmaMapper sigmaMapper;

    @Override
    public ResponseResult getFileDetails(HttpServletRequest request) {
        try {
            Integer id =(Integer) request.getSession().getAttribute("id");
            if(!ObjectUtils.isEmpty(id)){
                FileDetails  details = getDetails(id);
                return ResponseResult.ok(details);
            }else {
                throw new BusinessRuntimeException(ResultCodeEnum.NO_SESSION.getCode(),ResultCodeEnum.NO_SESSION.getMessage());
            }
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult getRank(HttpServletRequest request,String queue,Integer sort) {
        List<Ranks> ranks  = null;
        try {
            if(ObjectUtils.isEmpty(queue)){
                Integer id =(Integer) request.getSession().getAttribute("id");
                if(!ObjectUtils.isEmpty(id)){
                    FileDetails details = getDetails(id);
                    if(ObjectUtils.isEmpty(details)){
                        throw new BusinessRuntimeException(ResultCodeEnum.INCOMPLETE_USER_INFORMATION.getCode(),ResultCodeEnum.INCOMPLETE_USER_INFORMATION.getMessage());
                    }
                    Rank rank = getRank(details);
                    if(ObjectUtils.isEmpty(rank)){
                        throw new BusinessRuntimeException(ResultCodeEnum.HIGHEST_RANK.getCode(),ResultCodeEnum.HIGHEST_RANK.getMessage());
                    }
                    return ResponseResult.ok(rank);
                }else {
                    throw new BusinessRuntimeException(ResultCodeEnum.NO_SESSION.getCode(),ResultCodeEnum.NO_SESSION.getMessage());
                }
            }
            ranks = archivesMapper.getRanks(queue);
            Map map = new HashMap();
            map.put("ranks",ranks);
            if(!ObjectUtils.isEmpty(ranks)){
                if(!ObjectUtils.isEmpty(sort)){
                    map.put("Current_rank",sort);
                }
            }
            return ResponseResult.ok(map);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult getTitleInfo(HttpServletRequest request) {
        JobTitle titleInfo =null;
        try {
            Integer id =(Integer) request.getSession().getAttribute("id");
            if(!ObjectUtils.isEmpty(id)){
                titleInfo = archivesMapper.getTitleInfo(id);
            }else {
                throw new BusinessRuntimeException(ResultCodeEnum.NO_SESSION.getCode(),ResultCodeEnum.NO_SESSION.getMessage());
            }
            return ResponseResult.ok(titleInfo);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult getPanentInfo(HttpServletRequest request,Integer type) {
        List<Patentt> patentts=new ArrayList<>();
        try {
            if(ObjectUtils.isEmpty(type)){
               type=0;
            }
            if(type==0){
                Integer id =(Integer) request.getSession().getAttribute("id");
                if(!ObjectUtils.isEmpty(id)){
                    patentts = archivesMapper.getPanents(id);
                }else {
                    throw new BusinessRuntimeException(ResultCodeEnum.NO_SESSION.getCode(),ResultCodeEnum.NO_SESSION.getMessage());
                }
                if(!CollectionUtils.isEmpty(patentts)){
                    for (Patentt patentt : patentts) {
                        User user = userMapper.selectByPrimaryKey(patentt.getUserId());
                        if(ObjectUtils.isEmpty(user)){
                            continue;
                        }
                        if(ObjectUtils.isEmpty(user.getUsername())){
                            continue;
                        }
                        patentt.setUserName(user.getUsername());
                    }
                }

            }else{
                    Integer id =(Integer) request.getSession().getAttribute("id");
                    if(!ObjectUtils.isEmpty(id)){
                        patentts = archivesMapper.getPanentInfo(id, type);
                        User user = userMapper.selectByPrimaryKey(id);
                        if(!CollectionUtils.isEmpty(patentts)){
                            for (Patentt patentt : patentts) {
                                if(ObjectUtils.isEmpty(user)){
                                    continue;
                                }
                                if(ObjectUtils.isEmpty(user.getUsername())){
                                    continue;
                                }
                                patentt.setUserName(user.getUsername());
                            }
                        }
                    }else {
                        throw new BusinessRuntimeException(ResultCodeEnum.NO_SESSION.getCode(),ResultCodeEnum.NO_SESSION.getMessage());
                    }
            }
            return ResponseResult.ok(patentts);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult getPanent(Integer id) {
        try {
            if(ObjectUtils.isEmpty(id)){
                throw new BusinessRuntimeException(ResultCodeEnum.INCORRECTPARAM_CODE.getCode(),ResultCodeEnum.INCORRECTPARAM_CODE.getMessage());
            }
            Patentt patent = archivesMapper.getPanent(id);
            if(!ObjectUtils.isEmpty(patent)){
                if(!ObjectUtils.isEmpty(patent.getUserId())){
                    User user = userMapper.selectByPrimaryKey(patent.getUserId());
                    if(!ObjectUtils.isEmpty(user) && !ObjectUtils.isEmpty(user.getUsername())){
                        patent.setUserName(user.getUsername());
                    }
                }
            }
            return ResponseResult.ok(patent);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult getProject(HttpServletRequest request,Integer projectlevel) {
        try {
            if(ObjectUtils.isEmpty(projectlevel)){
                projectlevel=1;
            }
            List<Projectt> projectts =null;
            Integer id =(Integer) request.getSession().getAttribute("id");
            if(!ObjectUtils.isEmpty(id)){
                projectts = archivesMapper.getProjects(id, projectlevel);
                    for (Projectt projectt : projectts) {
                        User user = userMapper.selectByPrimaryKey(id);
                        if(ObjectUtils.isEmpty(user)){
                            continue;
                        }
                        if(ObjectUtils.isEmpty(user.getUsername())){
                            continue;
                        }
                        projectt.setUserName(user.getUsername());
                    }
            }else {
                throw new BusinessRuntimeException(ResultCodeEnum.NO_SESSION.getCode(),ResultCodeEnum.NO_SESSION.getMessage());
            }
            return ResponseResult.ok(projectts);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult getProjectInfo(Integer id) {
        try {
            if(ObjectUtils.isEmpty(id)){
                throw new BusinessRuntimeException(ResultCodeEnum.INCORRECTPARAM_CODE.getCode(),ResultCodeEnum.INCORRECTPARAM_CODE.getMessage());
            }
            Projectt project = archivesMapper.getProject(id);
            if(!ObjectUtils.isEmpty(project)){
                if(!ObjectUtils.isEmpty(project.getUserId())){
                    User user = userMapper.selectByPrimaryKey(project.getUserId());
                    if(!ObjectUtils.isEmpty(user) && !ObjectUtils.isEmpty(user.getUsername())){
                        project.setUserName(user.getUsername());
                    }
                }
            }
            return ResponseResult.ok(project);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult getPer(HttpServletRequest request) {
        Map map = new HashMap();
        List<PerForMance> performance= new ArrayList<>();
        try {
            Integer id =(Integer) request.getSession().getAttribute("id");
            if(!ObjectUtils.isEmpty(id)){
                 performance = archivesMapper.getPer(id);
                FileDetails details = getDetails(id);
                if(!CollectionUtils.isEmpty(performance)){
                    map.put("performances",performance);
                }else{
                    map.put("performances",performance);
                }
                if(!ObjectUtils.isEmpty(details.getUsername())){
                    map.put("username",details.getUsername());
                }
                if(!ObjectUtils.isEmpty(details.getPhoto())){
                    map.put("photo",details.getPhoto());
                }
            }else {
                throw new BusinessRuntimeException(ResultCodeEnum.NO_SESSION.getCode(),ResultCodeEnum.NO_SESSION.getMessage());
            }
            return ResponseResult.ok(map);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult getTimes(HttpServletRequest request) {
        int timeClass=0;
        int timeAttendance=0;
        Map<String,Integer> map=new HashMap<>();
        try {
            Integer id =(Integer) request.getSession().getAttribute("id");
            if(!ObjectUtils.isEmpty(id)){
                List<Integer> classTime = archivesMapper.getClassTime(id);
                List<Integer> attendanceTime = archivesMapper.getAttendanceTime(id);
                if(!CollectionUtils.isEmpty(classTime)){
                    for (Integer c : classTime) {
                        if(ObjectUtils.isEmpty(c)){
                            continue;
                        }
                        timeClass +=c;
                    }
                }
                if(!CollectionUtils.isEmpty(attendanceTime)){
                    for (Integer a : attendanceTime) {
                        if(ObjectUtils.isEmpty(a)){
                            continue;
                        }
                        timeAttendance +=a;
                    }
                }
            }else {
                throw new BusinessRuntimeException(ResultCodeEnum.NO_SESSION.getCode(),ResultCodeEnum.NO_SESSION.getMessage());
            }
            map.put("classTime",timeClass);
            map.put("attendanceTime",timeAttendance);
            return ResponseResult.ok(map);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult setApproval(HttpServletRequest request) {
        try {
            Integer id = (Integer) request.getSession().getAttribute("id");
            if (!ObjectUtils.isEmpty(id)) {
                Example example = new Example(RankApproval.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("userId" ,id);
                criteria.andEqualTo("status" ,1);
                int i = rankApprovalMapper.selectCountByExample(example);
                if(i>0){
                    throw new BusinessRuntimeException(ResultCodeEnum.APPLICATION_IN_PROGRESS.getCode(),ResultCodeEnum.APPLICATION_IN_PROGRESS.getMessage());
                }
                FileDetails details = getDetails(id);
                if(ObjectUtils.isEmpty(details)){
                    throw new BusinessRuntimeException(ResultCodeEnum.INCOMPLETE_USER_INFORMATION.getCode(),ResultCodeEnum.INCOMPLETE_USER_INFORMATION.getMessage());
                }
                String detentionTime = details.getDetentionTime();
                Rank rank = getRank(details);
                if(ObjectUtils.isEmpty(rank)){
                    throw new BusinessRuntimeException(ResultCodeEnum.HIGHEST_RANK.getCode(),ResultCodeEnum.HIGHEST_RANK.getMessage());
                }
                if(!ObjectUtils.isEmpty(detentionTime) ){
                    Float aFloat = Float.valueOf(detentionTime);
                    if(aFloat >=rank.getUptime()){
                        RankApproval approval=new RankApproval();
                        approval.setUserId(id);
                        approval.setUsername(details.getUsername());
                        approval.setDeptName(details.getDeptName());
                        approval.setUpperRankName(details.getRankName());
                        approval.setNextRankId(rank.getId());
                        approval.setNextRankName(rank.getName());
                        approval.setJob(details.getJob());
                        approval.setEduKind(details.getEduKind());
                        approval.setHiredDate(details.getHiredDate());
                        approval.setDetentionTime(detentionTime);
                        approval.setStatus(1);
                        approval.setCreationTime(new Date());
                        rankApprovalMapper.insertSelective(approval);
                    }else{
                        throw new BusinessRuntimeException(ResultCodeEnum.INSUFFICIENT_YEARS.getCode(),ResultCodeEnum.INSUFFICIENT_YEARS.getMessage());
                    }
                }else{
                    throw new BusinessRuntimeException(ResultCodeEnum.INCOMPLETE_PROMOTION_INFORMATION.getCode(),ResultCodeEnum.INCOMPLETE_PROMOTION_INFORMATION.getMessage());
                }
            }else {
                throw new BusinessRuntimeException(ResultCodeEnum.NO_SESSION.getCode(),ResultCodeEnum.NO_SESSION.getMessage());
            }
            return ResponseResult.ok();
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult getSix(HttpServletRequest request) {
        SixSigma sigma=null;
        try {
            Integer id =(Integer) request.getSession().getAttribute("id");
            if(!ObjectUtils.isEmpty(id)){
                sigma = sigmaMapper.getSixSigma(id);
                return ResponseResult.ok(sigma);
            }else {
                throw new BusinessRuntimeException(ResultCodeEnum.NO_SESSION.getCode(),ResultCodeEnum.NO_SESSION.getMessage());
            }
        } catch (BusinessRuntimeException e) {
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult approval(HttpServletRequest request) {
        try {
            Integer id =(Integer) request.getSession().getAttribute("id");
            List<ApprovalRank>  rankApprovals =new ArrayList<>();
            if(!ObjectUtils.isEmpty(id)){
                rankApprovals = archivesMapper.select(id);
            }else{
                throw new BusinessRuntimeException(ResultCodeEnum.NO_SESSION.getCode(),ResultCodeEnum.NO_SESSION.getMessage());
            }
            return ResponseResult.ok(rankApprovals);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }

    @Override
    public ResponseResult picture(MultipartFile file, HttpServletRequest request) {
        try {
            String url= ReadPropertiesUtil.readUrl("picture_url");
            String s = null;
            try {
                s = FileTool.upLoad(file, url);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Integer id =(Integer) request.getSession().getAttribute("id");
            if(!ObjectUtils.isEmpty(id)){
                User user=new User();
                user.setId(id);
                user.setPhoto(s);
                Example example =new Example(User.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("id",id);
                userMapper.updateByExampleSelective(user,example);
            }else {
                throw new BusinessRuntimeException(ResultCodeEnum.NO_SESSION.getCode(),ResultCodeEnum.NO_SESSION.getMessage());
            }
            return ResponseResult.ok(s);
        } catch (BusinessRuntimeException e) {
            e.printStackTrace();
            return ResponseResult.failure(e.getErrorCode(),e.getMessage());
        }
    }


    private FileDetails getDetails(Integer id){
        FileDetails fileDetails=new FileDetails();
        User user = userMapper.selectByPrimaryKey(id);
        if(ObjectUtils.isEmpty(user)){
            return fileDetails;
        }
        BeanUtils.copyProperties(user,fileDetails);
        Integer rankId = user.getRankId();
        Integer deptId = user.getDeptId();
        Integer eduId = user.getEduId();
        List<PerForMance> pers = archivesMapper.getPer(id);
        if(!CollectionUtils.isEmpty(pers)){
            String introduce = pers.get(0).getIntroduce();
            if(!ObjectUtils.isEmpty(introduce)){
                fileDetails.setPerintroduce(introduce);
            }
        }
        if(deptId!=null){
            Deptment deptment = archivesMapper.getDeptment(deptId);
            if(!ObjectUtils.isEmpty(deptment)){
                BeanUtils.copyProperties(deptment,fileDetails);
            }
        }
        if(eduId!=null){
            Eduu eduu = archivesMapper.getEdu(eduId);
            if(!ObjectUtils.isEmpty(eduu)){
                BeanUtils.copyProperties(eduu,fileDetails);
            }
        }
        if(rankId!=null){
            Rank rank = archivesMapper.getRank(rankId);
            if(!ObjectUtils.isEmpty(rank)){
                BeanUtils.copyProperties(rank,fileDetails);
                fileDetails.setRankId(rank.getId());
                fileDetails.setRankName(rank.getName());
            }
        }
        String s = null;
        if(user.getRankUpdate()!=null){
            Date rankUpdate = user.getRankUpdate();
             s = TimeUtil.yearCompare(rankUpdate);
        }
        if(user.getUsername()!=null){
            fileDetails.setUsername(user.getUsername());
        }
        if(user.getJob()!=null){
            fileDetails.setJob(user.getJob());
        }
        if(user.getHiredDate()!=null){
            fileDetails.setHiredDate(user.getHiredDate());
        }
        fileDetails.setDetentionTime(s);
        return fileDetails;
    }

    private Rank getRank(FileDetails details){
        Rank rank = new Rank();
        Integer sort = details.getSort();
        String queue = details.getQueue();
        if(!ObjectUtils.isEmpty(sort) && !ObjectUtils.isEmpty(queue)) {
            Example rankExample = new Example(Rank.class);
            Example.Criteria rankCriteria = rankExample.createCriteria();
            rankCriteria.andEqualTo("sort", sort + 1);
            rankCriteria.andEqualTo("queue", queue);
            rank = rankMapper.selectOneByExample(rankExample);
            return rank;
        }else{
            throw new BusinessRuntimeException(ResultCodeEnum.INCOMPLETE_PROMOTION_INFORMATION.getCode(),ResultCodeEnum.INCOMPLETE_PROMOTION_INFORMATION.getMessage());
        }
    }

}